package com.xxx.blog.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.blog.domain.Article;
import com.xxx.blog.query.ArticleQuery;
import com.xxx.blog.service.impl.ArticleServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/article")
@Api(tags = "文章管理接口")
public class ArticleController {
    @Autowired
    private ArticleServiceImpl articleService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public R<List<Article>> findAll() {
        List<Article> articleList = articleService.findAll();
        return R.ok(articleList);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询一个")
    public R<Article> findOne(@PathVariable Long id) {
        Article article = articleService.findOne(id);
        return R.ok(article);
    }

    @PostMapping
    @ApiOperation(value = "分页查询")
    public R<PageInfo<Article>> queryPage(@RequestBody ArticleQuery articleQuery) {
        List<Article> articleList = articleService.queryPage(articleQuery);
        PageInfo<Article> info = new PageInfo<>(articleList);
        return R.ok(info);
    }

    @PutMapping
    @ApiOperation(value = "添加或修改")
    public R<Void> addOrUpdateArticle(@RequestBody Article article) {
        try {
            Long id = article.getId();
            if (id == null) {
                articleService.addArticle(article);
            } else {
                articleService.updateArticle(article);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除一个")
    public R<Void> delete(@PathVariable Long id) {
        try {
            articleService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PatchMapping
    @ApiOperation("批量删除")
    public R<Void> batchDeletes(@RequestBody Long[] ids) {
        try {
            articleService.batchDeletes(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }
}
